package org.example.modules.user.service.Impl;

import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.example.common.utils.ThreadLocalUtil;
import org.example.modules.user.entry.User;
import org.example.modules.user.entry.UserAddress;
import org.example.modules.user.mapper.UserAddressMapper;
import org.example.modules.user.mapper.UserMapper;
import org.example.modules.user.service.UserAddressService;
import org.example.modules.user.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.List;

/**
 * @Description UserAddressServiceImpl
 * @Author xiaotian
 * @Date 2025-04-17
 */
@Service
public class UserAddressServiceImpl extends ServiceImpl<UserAddressMapper,UserAddress> implements UserAddressService {

    @Autowired
    private UserAddressMapper userAddressMapper;

    @Autowired
    private UserMapper userMapper;

    @Override
    public void saveAddress(JSONObject data) {
        UserAddress userAddress = new UserAddress();
        userAddress = data.toJavaObject(UserAddress.class);
        User user = userMapper.selectUser(ThreadLocalUtil.getUserId());
        if(userAddress.getId()==null){
            userAddress.setUserId(user.getId());
            userAddressMapper.insert(userAddress);
        }else{
            LambdaQueryWrapper<UserAddress> lambdaQueryWrapper = new LambdaQueryWrapper<>();
            lambdaQueryWrapper.eq(UserAddress :: getId,userAddress.getId());
            userAddressMapper.update(userAddress,lambdaQueryWrapper);
        }
    }

    @Override
    public List<UserAddress> getAllAddress() {
        User user = userMapper.selectUser(ThreadLocalUtil.getUserId());
        List<UserAddress> userAddressesList = userAddressMapper.selectAll(user.getId());
        return userAddressesList;
    }

    @Override
    public void updateDefaultAddress(JSONObject data) {
        Integer userId = data.getInteger("userId");
        userAddressMapper.updateDefault(userId);
        Integer Id = data.getInteger("id");
        userAddressMapper.updateIsDefault(userId,Id);
    }

    @Override
    public UserAddress getDefaultAddress() {
        User user = userMapper.selectUser(ThreadLocalUtil.getUserId());
        LambdaQueryWrapper<UserAddress> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(UserAddress::getUserId,user.getId()).eq(UserAddress::getIsDefault,1);
        return userAddressMapper.selectOne(lambdaQueryWrapper);
    }
}
